package com.zx._12_算法.algorithm.letcode;

/**
 * @version v1.0
 * @Project: knowledge
 * @Title: 数字生成短链
 * @Description:翻转数组
 * @author: zhangxue
 * @date: 2020年3月25日下午5:45:24
 * @company: 未知
 * @Copyright: Copyright (c) 2015
 */
public class Demo2 {

    public static void main(String[] args) {
        Node head = new Node(1, null);
        Node node1 = new Node(2, null);
        head.next = node1;
        Node node2 = new Node(3, null);
        node1.next = node2;
        Node node3 = new Node(4, null);
        node2.next = node3;
        Node node4 = new Node(5, null);
        node3.next = node4;

//		Node reverse1 = reverse1(head);
//		while (reverse1 != null) {
//			System.out.println(reverse1.data);
//			reverse1 = reverse1.next;
//		}

        Node reverse2 = reverse2(head);
        while (reverse2 != null) {
            System.out.println(reverse2.data);
            reverse2 = reverse2.next;
        }


    }

    /**
     * @param node
     * @Title: 二支针法遍历翻转
     * @date: 2020年3月26日上午10:18:22
     * @author: zhangxue
     */
    public static Node reverse1(Node node) {
        Node now = node;// 当前的节点
        Node next = now.next;//先获得第二个节点
        now.next = null;

        while (next != null) {
            Node nextNext = next.next;
            // 引用翻转
            next.next = now;
            // 指定下次轮询翻转的对象
            now = next;
            next = nextNext;
        }
        return now;
    }

    /**
     * @param node
     * @return
     * @Title: 递归翻转
     * @date: 2020年3月26日上午10:27:11
     * @author: zhangxue
     */
    public static Node reverse2(Node node) {
        Node now = node;// 当前的节点
        Node next = now.next;//下个节点
        now.next = null;
        // next = null 的话就不用翻转了
        if (next == null) {
            return now;//其实就是最后一个节点,方便后面遍历打印
        } else {
            // 翻转后面的
            Node reverse = reverse2(next);
            // 进行翻转
            next.next = now;
            return reverse;
        }
    }

    private static class Node {

        int data;
        Node next;

        public Node(int data, Node next) {
            super();
            this.data = data;
            this.next = next;
        }
    }


}
